package com.cti.ftpservice.ftp;

import org.apache.log4j.Logger;

import com.cti.ftpservice.ftp.CommonsFtpUtils.UploadStatus;
import com.cti.ftpservice.model.FtpServiceInfo;
import com.ctibook.booksystem.ws.FtpFileUploadInfoViewVo;

public class FTPUploadFiles implements Runnable{

	    private FtpServiceInfo ftpUpLoadParams;
	    public static Logger logger = Logger.getLogger(FTPUploadFiles.class);
		public FTPUploadFiles(FtpServiceInfo _ftpUpLoadParams){
			ftpUpLoadParams=_ftpUpLoadParams;
		}
		
	@Override
	public void run() {
		FtpFileUploadInfoViewVo upPath=null;
		try {
			 if(ftpUpLoadParams==null){
				 return;
			 }
			 while(!ftpUpLoadParams.getStop()){
				 try {
					 if(ftpUpLoadParams.getDealCount()==ftpUpLoadParams.getBookTotalCount()){
						 ftpUpLoadParams.stopUpLoadFiles();
						 logger.info(ftpUpLoadParams.getFtpServiceName()+"服务器所有文件均已经开始处理");
					 }
					 while(ftpUpLoadParams.getPause()){
						 wait();
					 }
					 while ((upPath=ftpUpLoadParams.getFirstUpLoadFilePath())==null) {
						return;
					}
					 if(upPath!=null){
						 logger.info(Thread.currentThread().getName()+"开始上传文件："+upPath);
						 FTPClientHelper ftpClient=new FTPClientHelper();
						 if(!ftpClient.isConnected())
						    CommonsFtpUtils.connect(ftpClient,ftpUpLoadParams.getFtpURL(), new java.lang.Integer(ftpUpLoadParams.getFtpport()), ftpUpLoadParams.getUsername(), ftpUpLoadParams.getPwd());
						 UploadStatus status= CommonsFtpUtils.upload(ftpClient, upPath.getLocalFtpFilePath(),upPath.getDownloadFtpFilePath());
						 CommonsFtpUtils.disconnect(ftpClient);
						 ftpUpLoadParams.adduploadDealItem(upPath,status.equals(UploadStatus.Upload_New_File_Success));
						 logger.info(Thread.currentThread().getName()+"成功上传文件："+upPath+"; 已经处理上传"+ftpUpLoadParams.getDealCount()+"个文件");
				  }
				  Thread.yield(); 
			      if (Thread.currentThread().isInterrupted()) {
			             throw new InterruptedException("Stopped by if Interrupted Stop()");
			      }
				} catch (Exception e) {
					if(upPath!=null)
						 ftpUpLoadParams.addUploadFilePath(upPath);
					 logger.info(e.getMessage());	
				}
	       } 
		} catch (Exception e) {
			 logger.info(e.getMessage());	
		}
	}
	

}
